// pages/my/my.js
var app = getApp()
Page({
  data: {
    agentId:'',
    accountId:'',
    putInCart:false,
    //优惠券
    coupon:false,couponInfo:'',couponList:[],couponMark:0,
    goodsAttr:[],
    currentItem:'',
    currentIndex:'',
    currentBox:[],
    isStock:false,
    enterCart:true,
    buyType:1,
    //商品信息
    name:'',imgUrl:'',price:'',sales:'',stock:'',productId:'',goodsType:'',thumbUrl:'',stockPrice:'',companyName:'',color:'',number1:'',number2:'',number3:'',setPrice1:'',setPrice2:'',setPrice3:'',mtcId:'',mtcName:'',togetherPrice:'',
    //厂家信息
    brand_url:'',brand_desc:'',brand_name:'',brand:true,manufacturer_id:'',
    //配送信息
    logistics:'',
    //商品详情
    details:[],
    num:1,
    actPrice:'',
    totalPrice:'',
    versionValueIds:'',
    ver_value_ids:'',
    typeDetailList:'',
    product_code:'',
    isShare:true,
    isTogether:true,
    togetherList:[],
    timeList:[]
  },
  onLoad: function (options) {
    let goodsType = options.goodsType,
    companyName = options.company,
    color = options.color,
    goodsId = options.id,
    buyType = options.buyType//0拼单1批发
    this.setData({
      productId:goodsId,
      goodsType,
      companyName,
      color,
      buyType
    })
    app.getMemInfo().then(res=>{
      let agentId = res.data.agentId
      let accountId = res.data.id
      // this.creatCurrentBox(agentId,goodsType,goodsId)
      this.setData({
        agentId,
        accountId
      })
      this.getGoodsDetail(options.id)
    })
    if (options.type==1) {
      this.setData({
        isStock:true
      })
    }
    // wx.showShareMenu({
    //     withShareTicket: true
    //   })
    // this.getPrice()
    
  },
  onShow(){


  },
  onShareAppMessage(res) {
    if (res.from === 'button') {
      console.log(res.target)
    }
    return {
      title: this.data.name,
    }
  },
  bindBuy(){
    this.setData({
      putInCart:true,
      enterCart:false
    })
  },
  //加入购物车
  bindEnterCart(){
    this.setData({
      putInCart:true,
      enterCart:true
    })
  },
  bindClose(){
    this.setData({
      putInCart:false
    })
  },
  //选择属性
  bindChoseAttr(e){
    let id = e.currentTarget.dataset.id
    let name = e.currentTarget.dataset.name
    let ids = e.currentTarget.dataset.ids
    let currentBox = this.data.currentBox
    const that = this
    currentBox.forEach((item,i)=>{
      if (item.id==id) {
        item.current=true
      }else{
        item.current=false
      }
    })
    this.setData({
      currentBox,
      ver_value_ids:ids,
      versionValueIds:id,
      currentItem:name
    })
    // this.getPrice()
  },
  //根据商品规格获取库存信息，价格，库存量
  getPrice(){
    // this.getVersions()
    var that = this
    let data = {
      skuId:this.data.versionValueIds
    }
    console.log(data)
    app.request('wx_app/product/version/stockInfo',data,'GET').then(res=>{
      console.log(res)
      that.setData({
        stock:res.data.stock,
        actPrice:res.data.price,
        stockPrice:res.data.stockPrice,
        thumbUrl:res.data.thumbUrl,
        totalPrice:res.data.price*that.data.num
      })
    })
  },
  getVersions(){
    let versions = []
    let verSort = []
    let versionValueIds =''
    this.data.currentBox.forEach(item=>{
      this.setData({
        versionValueIds:item.id
      })
    })
    // versions.forEach(item=>{
    //   if (item!='') {
    //     verSort.push(parseInt(item))
    //   }
    // })
    // verSort.sort().forEach(item=>{
    //   versionValueIds+=item+','
    // })
    // this.setData({
    //   versionValueIds:versionValueIds.substr(0,versionValueIds.length-1)
    // })
  },
  //初始化商品规格
  creatCurrentBox(agentId,type,productId){
    var that = this
    var data={
      type:0,
      productId
    }
    console.log(data)
    app.request('wx_app/product/version/list',data,'GET').then(res=>{
      console.log(res)
      let goodsAttr = []
      let attr = []
      //获取商品id的属性名放入content中
      res.data.versions.forEach((item,i)=>{
        let typesId = []
        goodsAttr.push({
          name:item.versionValue,
          id:item.id,
          ids:item.versionValueIds
        })
      })
      that.setData({
        goodsAttr
      })
      //获取默认属性放入currentBox
      let currentBox = []
      that.data.goodsAttr.forEach((item,i)=>{
        currentBox.push({
          name:item.versionValue,
          id:item.id,
          current:false
        })
      })
      currentBox[0].current=true
      that.setData({
        currentBox,
        versionValueIds:res.data.versions[0].id,
        ver_value_ids:res.data.versions[0].versionValueIds
      })
      // let typeList=''
      // that.data.currentBox.forEach(item=>{
      //   typeList+=item.item.id+','
      // })
      // that.setData({
      //   versionValueIds:typeList.substr(0, typeList.length - 1)
      // })
      that.getPrice()
    })
  },
  //将物品加入购物车
  bindPutInCart(){
    let that = this
    wx.getStorage({
      key: 'memInfo',
      success(res){
        let data = {
          agentId:that.data.agentId,
          productType:that.data.productType,
          stockSkuId:that.data.productId,
          productName:that.data.name,
          price:that.data.stockPrice==null?0:that.data.stockPrice,
          thumbUrl:that.data.imgUrl,
          count:1,
          manufacturerId:that.data.manufacturerId,
          accountId:that.data.accountId,
          versionValues:that.data.versionValues,
          versionNameId:that.data.versionNameId,
          mtcId:that.data.mtcId,
          mtcName:that.data.mtcName,
        }
        app.request('wx_app/stock_cart/saveStockCart',data,'GET').then(res=>{
          console.log(res)
          if (res.code==1) {
            app.errorMsg('加入进货单成功')
          }
        })
      },
      fail(){
        wx.navigateTo({
          url:'../../index/index'
        })
      }
    })
  },
  //结算
  bindConfirmPut(){
    let that = this
    wx.getStorage({
      key: 'memInfo',
      success(res) {
        let data = {
          agentId:that.data.agentId,
          productType:that.data.productType,
          stockSkuId:that.data.productId,
          productName:that.data.name,
          price:that.data.stockPrice==null?0:that.data.stockPrice,
          thumbUrl:that.data.imgUrl,
          count:1,
          manufacturerId:that.data.manufacturerId,
          accountId:that.data.accountId,
          versionValues:that.data.versionValues,
          versionNameId:that.data.versionNameId,
          mtcId:that.data.mtcId,
          mtcName:that.data.mtcName,
        }
        console.log(data)
        app.request('wx_app/stock_cart/saveStockCart',data,'GET').then(res=>{
          console.log(res)
          wx.navigateTo({
            url:'purchaseSettlement'
          })
        })
      },
      fail(){
        wx.navigateTo({
          url:'../../index/index'
        })
      }
    })
  },
  //进入订货单
  bindToCart(){
    wx.getStorage({
      key: 'memInfo',
      success(res) {
        wx.navigateTo({
          url:'purchaseSettlement'
        })
      },
      fail(){
        wx.navigateTo({
          url:'../../index/index'
        })
      }
    })
  },
  //获得商品详情
  getGoodsDetail(stockSkuId){
    wx.showLoading({
      title:'正在加载'
    })
    var data = {
      accountId:this.data.accountId,
      stockSkuId,
    }
    console.log(data)
    var that = this
    app.request('wx_app/product/detail',data,'GET').then(res=>{
      console.log(res)
      if (res.code==1) {
        let ros = res.data.stockSku
        let details = []
        details.push(ros.imgUrl2,ros.imgUrl3,ros.imgUrl4,ros.imgUrl5)
        if (res.data.isCoupon!=0){
          that.setData({
            couponInfo:res.data.isCoupon
          })
        }
        that.setData({
          isCoupon:res.data.isCoupon==0?0:1,
          name:ros.productName,
          imgUrl:ros.mainImgUrl,
          applyTo:ros.applyTo,
          price:ros.price,
          togetherPrice:ros.togetherPrice,
          brand_url:res.data.brand_url?res.data.brand_url:'',
          brand_desc:res.data.brand_desc?res.data.brand_desc:'',
          brand_name:res.data.brand_name?res.data.brand_name:'',
          colorName:ros.colorName,
          id:ros.id,
          deliberation:ros.deliberation,
          number1:ros.number1,
          number2:ros.number2,
          number3:ros.number3,
          setPrice1:ros.setPrice1,
          setPrice2:ros.setPrice2,
          setPrice3:ros.setPrice3,
          productType:ros.productType,
          sales:ros.sales,
          stock:ros.stock,
          stockPrice:ros.stockPrice,
          product_type:ros.versionValues+' '+ros.colorName,
          versionNameId:ros.versionNameId,
          versionValues:ros.versionValues,
          manufacturerId:ros.manufacturerId,
          mtcId:ros.mtcId,
          mtcName:ros.mtColorName,
          details
        })
        if (!res.data.brand_name) {
          that.setData({
            brand:false
          })
        }else{
          that.setData({
            brand:true
          })
        }
        this.getCouponList(ros.id)
        this.getTogetherList(ros.id)
        wx.hideLoading()
      }else{
        wx.hideLoading()
        app.errorMsg(res.message)
      }
    })
  },
  add(e){
    let num = e.currentTarget.dataset.num
    num++
    let price = this.data.actPrice
    this.setData({
      num,
      totalPrice:this.data.actPrice?this.data.actPrice*num:this.data.price*num
    })
  },
  sub(e){
    let num = e.currentTarget.dataset.num
    num--
    let price = this.data.actPrice

    if (num>0) {
      this.setData({
        num,
        totalPrice:price*num
      })
    }
  },
  getUserLoginSttus(){

  },
  shouye(){
    wx.navigateTo({
      url:'../../index/index'
    })
  },
  //打开优惠券
  openCoupon(){
    this.setData({
      coupon:true
    })
  },
  closeCoupon(){
    this.setData({
      coupon:false
    })
  },
  //获取优惠券列表
  getCouponList(skuId){
    let data = {
      accountId:this.data.accountId,
      skuId
    }
    console.log(data)
    app.request('wx_app/coupon/getCouponBySkuId',data,'GET').then(res=>{
      console.log(res)
      if (res.code==1) {
        let date = new Date()
        let couponMark = 0
        res.data.forEach((item,i)=>{
          item.start_date = item.begin_time.split('T')[0];
          item.end_date = item.end_time.split('T')[0]
          if ( item.is_use==null || item.is_use==0 ) {
            couponMark+=1
            this.setData({
              ['couponList['+i+']']:item
            })
          }
        })
        this.setData({
          couponMark
        })
      }else{
        app.errorMsg(res.message)
      }
    })
  },
  //领取优惠券
  getCoupon(e){
    let couponSkuId = e.currentTarget.dataset.id
    let data = {
      accountId:this.data.accountId,
      couponSkuId
    }
    app.request('wx_app/coupon/receiveCoupon',data,'GET').then(res=>{
      console.log(res)
      if (res.code==1) {
        app.errorMsg('领取成功')
        this.getCouponList(this.data.id)
      }else{
        app.errorMsg(res.message)
      }
    })
  },
  //获取拼单列表
  getTogetherList(stockSkuId){
    let that = this
    let data = {
      stockSkuId
    }
    console.log(data)
    app.request('wx_app/together/getListByStockSkuId',data,'GET').then(res=>{
      console.log(res)
      if (res.code==1) {
        this.setData({
          togetherList:res.data
        })
        setInterval(function () {
          that.timeShow()
        }, 1000)
      }else{
        app.errorMsg(res.message)
      }
    })
  },
  //拼单倒计时
  timeShow(){
    let that = this
    let timeList = []
    this.data.togetherList.forEach(item=>{
      timeList.push({
        start:item.createTime
      })
    })
    timeList.forEach(item=>{
      let end = new Date(parseInt(item.start + 86400)*1000)
      let now = new Date()
      //总秒数
      let totalSeconds = parseInt((end - now) / 1000);
      //小时数
      item.hour = Math.floor(totalSeconds / (60 * 60));
      //取余
      let modulo = totalSeconds % (60 * 60);
      //分钟
      item.minutes = Math.floor(modulo / 60);
      //秒
      item.seconds = modulo % 60;
    })
    this.setData({
      timeList
    })
  },
  //拼单详情
  moreTogether(){
    this.setData({
      isTogether:false
    })
  },
  //关闭拼单详情
  closeTogether(){
    this.setData({
      isTogether:true
    })
  },
  togetherBuy(){
    let data = {
      agentId:this.data.agentId,
      accountId:this.data.accountId,  
      stockSkuId:this.data.id,  
      togetherId:''
    }
    console.log(data)
    app.request('wx_app/together/saveAgentOrderByCart',data,'GET').then(res=>{
      console.log(res)
      if (res.code==1) {
        let orderId = res.data.id
        wx.navigateTo({
          url:'confirmOrder?orderId=' + orderId + '&applyType=0' + '&type=1' //0批发1拼单
        })
      }else{
        app.errorMsg(res.message)
      }
    })
  },
  //去拼单
  goTogether(e){
    let data = {
      agentId:this.data.agentId,
      accountId:this.data.accountId,  
      stockSkuId:this.data.id,  
      togetherId:e.currentTarget.dataset.id
    }
    console.log(data)
    app.request('wx_app/together/saveAgentOrderByCart',data,'GET').then(res=>{
      console.log(res)
      if (res.code==1) {
        let orderId = res.data.id
        wx.navigateTo({
          url:'confirmOrder?orderId=' + orderId + '&applyType=0' + '&type=1' //0批发1拼单
        })
      }else{
        app.errorMsg(res.message)
      }
    })
  }
})
